﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Utilities;

namespace ManageTicket.Ticket
{
    public partial class frmNewTicket : frmBase
    {
        #region Contructor
        public frmNewTicket(string voucher_no)
        {
            InitializeComponent();
            Voucher_No = voucher_no;
        }
        #endregion

        #region Variable
        ManageTicket.Library.Control.ExecuteControl exeCtrl;

        //permission
        bool bAdd = false;
        bool bEdit = false;
        bool bDelete = false;
        bool bCancel = false;
        bool bSave = false;
        bool bFunction = false;
        bool bView = false;
        bool bFind = false;
        bool bExport = false;
        bool bSendmail = false;
        bool bPrint = false;

        clsMethod4All objMethod = new clsMethod4All();
        ManageTicket.Library.Common.CommonFunction clsCommonFunc = new ManageTicket.Library.Common.CommonFunction();
        private Business.Voucher boVoucher = new Business.Voucher();
        private Business.VoucherDetailBuy boVoucherBuy = new Business.VoucherDetailBuy();
        private Business.VoucherDetailSale boVoucherSale = new Business.VoucherDetailSale();
        private Business.VoucherHistory boVoucherHistory = new Business.VoucherHistory();
        private Business.Employee boEmployee = new Business.Employee();
        private Business.Customer boCustomer = new Business.Customer();
        private Business.Provider boProvider = new Business.Provider();
        private string Voucher_No = "";
        string sModel = ""; //Store AND or UPDATE status
        private const string ADD_MODEL = "ADD";
        private const string UPDATE_MODEL = "UPDATE";
        #endregion

        #region Event
        private void frmNewTicket_Load(object sender, EventArgs e)
        {
            //execute control
            exeCtrl = new ManageTicket.Library.Control.ExecuteControl();
            exeCtrl.Dock = DockStyle.Fill;
            exeCtrl.lblDescription.Text = "Cập nhật vé";
            pnlExe.Controls.Add(exeCtrl);

            //permission
            clsCommonFunc.GetPermission(ref bAdd, ref bEdit, ref bDelete, ref bCancel, ref bSave, ref bFunction, ref bView, ref bFind, ref bExport, ref bSendmail, ref bPrint, frmMain.CurrentUser.UserId, this.Name);

            GetListProvider();
            GetListCustomer();

            //get code type
            clsCommonFunc.GetListCodeType(cboCurrencyBuy, "CUR");
            clsCommonFunc.GetListCodeType(cboCurrencySale, "CUR");

            //set status
            LoadStatusOnce();

            if (Voucher_No != "")
            {
                DataObjects.Voucher oVou = boVoucher.GetObjectByPK(Voucher_No);
                if (oVou != null)
                {
                    sModel = UPDATE_MODEL;
                    FillData(oVou);
                    LoadStatus(false, true, true, true, true, true);
                    objMethod.en_dis_control(new Control[] { grpCommonInfo, tabDetail }, new Control[] { });
                }
            }
            else
            {
                LoadStatus(true, false, false, false, false, false);
                objMethod.en_dis_control(new Control[] { }, new Control[] { grpCommonInfo, tabDetail });
            }
        }

        private void txtEmployeeId_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                DataObjects.Employee oCus = boEmployee.GetObjectByPK(txtEmployeeId.Text);
                if (oCus != null)
                {
                    txtFullName.Text = oCus.LastName + " " + oCus.FirstName;
                    txtFullName.Focus();
                }
            }
        }

        private void dtpDateOfVoucher_ValueChanged(object sender, EventArgs e)
        {
            if (sModel == ADD_MODEL)
            {
                txtVoucherNo.Text = dtpDateOfVoucher.Value.ToString("yyyyMMdd") + clsCommonFunc.RuleNumber5(boVoucher.GetMaxID(dtpDateOfVoucher.Value.ToString("yyyyMMdd")) + 1);
                GetDiscountProvider();
                GetDiscountCustomer();
                CalculateBuy();
                CalculateSale();
                CalculateSaleDiscount(true);
            }
            
        }
        //buy
        private void cboProviderId_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboProviderId.SelectedIndex >= 0)
            {
                DataRowView drv = (DataRowView)cboProviderId.SelectedItem;
                txtProviderPersonRepresent.Text = drv.Row.ItemArray[2].ToString();

                GetDiscountProvider();
                CalculateBuy();
            }
        }
        
        private void cboCurrencyBuy_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboCurrencyBuy.DataSource != null)
            {
                if (cboCurrencyBuy.SelectedValue.ToString().ToUpper() == "CUR_1")
                {
                    txtExchangeBuy.Text = "1";
                    CalculateBuy();
                }
            }
        }

        private void grvDetailBuy_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            switch (grvDetailBuy.Columns[e.ColumnIndex].Name)
            {
                case "colFareBuy":
                    grvDetailBuy.Columns["colFareBuy"].ValueType = typeof(string);
                    CalcAmountBuy(e.RowIndex);
                    CalculateBuy();
                    break;
                case "colTaxBuy":
                    grvDetailBuy.Columns["colTaxBuy"].ValueType = typeof(string);
                    CalcAmountBuy(e.RowIndex);
                    CalculateBuy();
                    break;
                case "colAddOnBuy":
                    grvDetailBuy.Columns["colAddOnBuy"].ValueType = typeof(string);
                    CalcAmountBuy(e.RowIndex);
                    CalculateBuy();
                    break;
            }
        }

        private void grvDetailBuy_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            try
            {
                switch (grvDetailBuy.Columns[e.ColumnIndex].Name)
                {
                    case "colFrom":
                        grvDetailBuy.Columns["colFrom"].ValueType = typeof(string);
                        break;
                    case "colTo":
                        grvDetailBuy.Columns["colTo"].ValueType = typeof(string);
                        break;
                    case "colFltNo":
                        grvDetailBuy.Columns["colFltNo"].ValueType = typeof(string);
                        break;
                    case "colClass":
                        grvDetailBuy.Columns["colClass"].ValueType = typeof(string);
                        break;
                    case "colDeptDate":
                        grvDetailBuy.Columns["colDeptDate"].ValueType = typeof(string);
                        break;
                    case "colPNR":
                        grvDetailBuy.Columns["colPNR"].ValueType = typeof(string);
                        break;
                    case "colFareBuy":
                        grvDetailBuy.Columns["colFareBuy"].ValueType = typeof(double);
                        break;
                    case "colTaxBuy":
                        grvDetailBuy.Columns["colTaxBuy"].ValueType = typeof(double);
                        break;
                    case "colAddOnBuy":
                        grvDetailBuy.Columns["colAddOnBuy"].ValueType = typeof(double);
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void grvDetailBuy_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                switch (grvDetailBuy.Columns[e.ColumnIndex].Name)
                {
                    case "colFareBuy":
                        grvDetailBuy.Columns["colFareBuy"].ValueType = typeof(string);
                        break;
                    case "colTaxBuy":
                        grvDetailBuy.Columns["colTaxBuy"].ValueType = typeof(string);
                        break;
                    case "colAddOnBuy":
                        grvDetailBuy.Columns["colAddOnBuy"].ValueType = typeof(string);
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void grvDetailBuy_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            bool bHaveError = false;
            string sErrorMsg_RequiredFields = string.Empty;

            if (this.grvDetailBuy.IsCurrentRowDirty)
            {
                System.Windows.Forms.DataGridViewRow oDGVR = this.grvDetailBuy.Rows[e.RowIndex];

                if (oDGVR.Cells["colFrom"].Value == null)
                {
                    sErrorMsg_RequiredFields += "   Phải nhập From." + Environment.NewLine;
                    bHaveError = true;
                }
                else if (oDGVR.Cells["colFrom"].Value.ToString().Trim().Length < 1)
                {
                    sErrorMsg_RequiredFields += "   Phải nhập From." + Environment.NewLine;
                    bHaveError = true;
                }

                if (oDGVR.Cells["colTo"].Value == null)
                {
                    sErrorMsg_RequiredFields += "   Phải nhập To." + Environment.NewLine;
                    bHaveError = true;
                }
                else if (oDGVR.Cells["colTo"].Value.ToString().Trim().Length < 1)
                {
                    sErrorMsg_RequiredFields += "   Phải nhập To." + Environment.NewLine;
                    bHaveError = true;
                }

                if (oDGVR.Cells["colFltNo"].Value == null)
                {
                    sErrorMsg_RequiredFields += "   Phải nhập Flight No." + Environment.NewLine;
                    bHaveError = true;
                }
                else if (oDGVR.Cells["colFltNo"].Value.ToString().Trim().Length < 1)
                {
                    sErrorMsg_RequiredFields += "   Phải nhập Flight No." + Environment.NewLine;
                    bHaveError = true;
                }

                if (oDGVR.Cells["colClass"].Value == null)
                {
                    sErrorMsg_RequiredFields += "   Phải nhập Class." + Environment.NewLine;
                    bHaveError = true;
                }
                else if (oDGVR.Cells["colClass"].Value.ToString().Trim().Length < 1)
                {
                    sErrorMsg_RequiredFields += "   Phải nhập Class." + Environment.NewLine;
                    bHaveError = true;
                }

                if (oDGVR.Cells["colDeptDate"].Value == null)
                {
                    sErrorMsg_RequiredFields += "   Phải nhập Dept. Date." + Environment.NewLine;
                    bHaveError = true;
                }
                else if (oDGVR.Cells["colDeptDate"].Value.ToString().Trim().Length < 1)
                {
                    sErrorMsg_RequiredFields += "   Phải nhập Dept. Date." + Environment.NewLine;
                    bHaveError = true;
                }

                if (oDGVR.Cells["colFareBuy"].Value == null)
                {
                    sErrorMsg_RequiredFields += "   Phải nhập Fare." + Environment.NewLine;
                    bHaveError = true;
                }
                else if (oDGVR.Cells["colFareBuy"].Value.ToString().Trim().Length < 1)
                {
                    sErrorMsg_RequiredFields += "   Phải nhập Fare." + Environment.NewLine;
                    bHaveError = true;
                }

                if (bHaveError)
                {
                    oDGVR.ErrorText = sErrorMsg_RequiredFields;
                    e.Cancel = true;
                }

            }
        }           

        private void txtDiscountPercent_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtDiscountPercent.Text);
        }

        private void txtExchangeBuy_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtExchangeBuy.Text);
        }

        private void txtDiscountPercent_Leave(object sender, EventArgs e)
        {
            CalculateBuy();
        }

        private void txtExchangeBuy_Leave(object sender, EventArgs e)
        {
            CalculateBuy();
        }

        //sale
        private void cboCustomerId_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboCustomerId.SelectedIndex >= 0)
            {
                DataRowView drv = (DataRowView)cboCustomerId.SelectedItem;
                txtCustomerPersonRepresent.Text = drv.Row.ItemArray[2].ToString();

                GetDiscountCustomer();
                CalculateSaleDiscount(true);
            }
        }

        private void cboCurrencySale_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboCurrencySale.DataSource != null)
            {
                if (cboCurrencySale.SelectedValue.ToString().ToUpper() == "CUR_1")
                {
                    txtExchangeSale.Text = "1";
                    CalculateSale();
                }
            }
        }

        private void grvDetailSale_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            switch (grvDetailSale.Columns[e.ColumnIndex].Name)
            {
                case "colFareSale":
                    grvDetailSale.Columns["colFareSale"].ValueType = typeof(string);
                    CalcAmountSale(e.RowIndex);
                    CalculateSale();
                    break;
                case "colTaxSale":
                    grvDetailSale.Columns["colTaxSale"].ValueType = typeof(string);
                    CalcAmountSale(e.RowIndex);
                    CalculateSale();
                    break;
                case "colAddOnSale":
                    grvDetailSale.Columns["colAddOnSale"].ValueType = typeof(string);
                    CalcAmountSale(e.RowIndex);
                    CalculateSale();
                    break;
            }
        }

        private void grvDetailSale_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            try
            {
                switch (grvDetailSale.Columns[e.ColumnIndex].Name)
                {
                    case "colPassenger":
                        grvDetailSale.Columns["colPassenger"].ValueType = typeof(string);
                        break;
                    case "colTicketNo":
                        grvDetailSale.Columns["colTicketNo"].ValueType = typeof(string);
                        break;
                    case "colRemark":
                        grvDetailSale.Columns["colRemark"].ValueType = typeof(string);
                        break;
                    case "colFareSale":
                        grvDetailSale.Columns["colFareSale"].ValueType = typeof(double);
                        break;
                    case "colTaxSale":
                        grvDetailSale.Columns["colTaxSale"].ValueType = typeof(double);
                        break;
                    case "colAddOnSale":
                        grvDetailSale.Columns["colAddOnSale"].ValueType = typeof(double);
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void grvDetailSale_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                switch (grvDetailSale.Columns[e.ColumnIndex].Name)
                {
                    case "colFareSale":
                        grvDetailSale.Columns["colFareSale"].ValueType = typeof(string);
                        break;
                    case "colTaxSale":
                        grvDetailSale.Columns["colTaxSale"].ValueType = typeof(string);
                        break;
                    case "colAddOnSale":
                        grvDetailSale.Columns["colAddOnSale"].ValueType = typeof(string);
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void grvDetailSale_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            bool bHaveError = false;
            string sErrorMsg_RequiredFields = string.Empty;

            if (this.grvDetailSale.IsCurrentRowDirty)
            {
                System.Windows.Forms.DataGridViewRow oDGVR = this.grvDetailSale.Rows[e.RowIndex];

                if (oDGVR.Cells["colPassenger"].Value == null)
                {
                    sErrorMsg_RequiredFields += "   Phải nhập Tên hành khách." + Environment.NewLine;
                    bHaveError = true;
                }
                else if (oDGVR.Cells["colPassenger"].Value.ToString().Trim().Length < 1)
                {
                    sErrorMsg_RequiredFields += "   Phải nhập Tên hành khách." + Environment.NewLine;
                    bHaveError = true;
                }                

                if (oDGVR.Cells["colFareSale"].Value == null)
                {
                    sErrorMsg_RequiredFields += "   Phải nhập Giá vé." + Environment.NewLine;
                    bHaveError = true;
                }
                else if (oDGVR.Cells["colFareSale"].Value.ToString().Trim().Length < 1)
                {
                    sErrorMsg_RequiredFields += "   Phải nhập Giá vé." + Environment.NewLine;
                    bHaveError = true;
                }

                if (bHaveError)
                {
                    oDGVR.ErrorText = sErrorMsg_RequiredFields;
                    e.Cancel = true;
                }

            }
        }

        private void txtDiscountPrivateSalePercent_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtDiscountPrivateSalePercent.Text);
        }

        private void txtExchangeSale_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtExchangeSale.Text);
        }

        private void txtDiscountPrivateSale_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtDiscountPrivateSale.Text);
        }

        private void txtVATPercent_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtVATPercent.Text);
        }

        private void txtVATValue_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtVATValue.Text);
        }

        private void txtOtherTax_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtOtherTax.Text);
        }

        private void txtOtherCharge_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtOtherCharge.Text);
        }

        
        private void txtDiscountPrivateSalePercent_Leave(object sender, EventArgs e)
        {
            CalculateSaleDiscount(true);
        }

        private void txtDiscountPrivateSale_Leave(object sender, EventArgs e)
        {
            CalculateSaleDiscount(false);
        }

        private void txtVATPercent_Leave(object sender, EventArgs e)
        {
            CalculateSale();
        }

        private void txtVATValue_Leave(object sender, EventArgs e)
        {
            CalculateSale();
        }

        private void txtOtherTax_Leave(object sender, EventArgs e)
        {
            CalculateSale();
        }

        private void txtOtherCharge_Leave(object sender, EventArgs e)
        {
            CalculateSale();
        }

        private void txtExchangeSale_Leave(object sender, EventArgs e)
        {
            CalculateSale();
        }

        #endregion

        #region Execute
        public override void Add()
        {
            ClearText();
            sModel = ADD_MODEL;
            txtVoucherNo.Text = dtpDateOfVoucher.Value.ToString("yyyyMMdd") + clsCommonFunc.RuleNumber5(boVoucher.GetMaxID(dtpDateOfVoucher.Value.ToString("yyyyMMdd")) + 1);
            LoadStatus(false, false, true, true, false, false);
            objMethod.en_dis_control(new Control[] { grpCommonInfo, tabDetail }, new Control[] { });
            txtEmployeeId.Text = frmMain.CurrentUser.EmployeeId;
            DataObjects.Employee oEmp = boEmployee.GetObjectByPK(txtEmployeeId.Text);
            if (oEmp != null)
                txtFullName.Text = oEmp.LastName + " " + oEmp.FirstName;
            dtpDateOfVoucher.Focus();
        }

        public override void Delete()
        {
            try
            {
                if (txtVoucherNo.Text == "")
                    return;

                if (MessageBox.Show("Bạn có thực sự muốn xóa?", "Aquarius", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    //Check Existing in table
                    //if (this.CheckExitToDelete(oDept.DEPT_CODE)) {
                    //    MessageBox.Show(".", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //    return;
                    //}

                    //delete relative
                    boVoucherBuy.DeleteByVoucherNo(txtVoucherNo.Text);
                    boVoucherSale.DeleteByVoucherNo(txtVoucherNo.Text);
                    boVoucherHistory.DeleteByVoucherNo(txtVoucherNo.Text);

                    //delete
                    boVoucher.DeleteByPK(txtVoucherNo.Text);
                    
                    MessageBox.Show("Xóa vé thành công.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearText();
                    LoadStatus(true, false, false, false, false, false);
                    objMethod.en_dis_control(new Control[] { }, new Control[] { grpCommonInfo, tabDetail });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public override void Cancel()
        {
            ClearText();
            sModel = "";
            LoadStatus(true, false, false, false, false, false);
            objMethod.en_dis_control(new Control[] { }, new Control[] { grpCommonInfo, tabDetail });
        }

        public override void Save()
        {
            if (txtVoucherNo.Text == "")
            {
                return;
            }
            if (CheckValid())
            {   
                try
                {
                    DataObjects.Voucher oVou = new DataObjects.Voucher();
                    oVou.VoucherNo = txtVoucherNo.Text;
                    oVou.DateOfVoucher = dtpDateOfVoucher.Value;
                    oVou.EmployeeId = txtEmployeeId.Text;
                    oVou.Remark = txtRemark.Text;
                    oVou.Status = "CURRENT";
                    //provider
                    oVou.ProviderId = cboProviderId.Text;
                    oVou.ProviderPersonRepresent = txtProviderPersonRepresent.Text;
                    oVou.Vat = chkVAT.Checked;
                    oVou.TotalBuy = txtTotalBuy.Text != "" ? double.Parse(txtTotalBuy.Text) : 0;
                    oVou.DiscountPercent = txtDiscountPercent.Text != "" ? double.Parse(txtDiscountPercent.Text) : 0;
                    oVou.Discount = txtDiscount.Text != "" ? double.Parse(txtDiscount.Text) : 0;
                    oVou.SumBuy = txtSumBuy.Text != "" ? double.Parse(txtSumBuy.Text) : 0;
                    oVou.CurrencyBuy = cboCurrencyBuy.SelectedValue != null ? cboCurrencyBuy.SelectedValue.ToString() : "";
                    oVou.ExchangeBuy = txtExchangeBuy.Text != "" ? double.Parse(txtExchangeBuy.Text) : 0;
                    oVou.SumBuyVnd = txtSumBuyVND.Text != "" ? double.Parse(txtSumBuyVND.Text) : 0;
                    //customer
                    oVou.CustomerId = cboCustomerId.Text;
                    oVou.CustomerPersonRepresent = txtCustomerPersonRepresent.Text;
                    oVou.TotalSale = txtTotalSale.Text != "" ? double.Parse(txtTotalSale.Text) : 0;
                    oVou.DiscountPrivatePercent = txtDiscountPrivateSalePercent.Text != "" ? double.Parse(txtDiscountPrivateSalePercent.Text) : 0;
                    oVou.DiscountPrivate = txtDiscountPrivateSale.Text != "" ? double.Parse(txtDiscountPrivateSale.Text) : 0;

                    oVou.VatPercent = txtVATPercent.Text != "" ? double.Parse(txtVATPercent.Text) : 0;
                    oVou.VatValue = txtVATValue.Text != "" ? double.Parse(txtVATValue.Text) : 0;
                    oVou.OtherTax = txtOtherTax.Text != "" ? double.Parse(txtOtherTax.Text) : 0;
                    oVou.OtherCharge = txtOtherCharge.Text != "" ? double.Parse(txtOtherCharge.Text) : 0;
                    
                    oVou.SumSale = txtSumSale.Text != "" ? double.Parse(txtSumSale.Text) : 0;
                    oVou.CurrencySale = cboCurrencySale.SelectedValue != null ? cboCurrencySale.SelectedValue.ToString() : "";
                    oVou.ExchangeSale = txtExchangeSale.Text != "" ? double.Parse(txtExchangeSale.Text) : 0;
                    oVou.SumSaleVnd = txtSumSaleVND.Text != "" ? double.Parse(txtSumSaleVND.Text) : 0;
                    
                    if (sModel == ADD_MODEL)
                    {
                        if (CheckIsExist(oVou.VoucherNo))
                        {
                            MessageBox.Show("Số phiếu đã tồn tại.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            txtVoucherNo.Focus();
                            return;
                        }                        
                        boVoucher.Insert(oVou);
                        InsertVoucherHistory(oVou);
                    }
                    else if (sModel == UPDATE_MODEL)
                    {
                        boVoucher.Update(oVou);
                        UpdateVoucherHistory(oVou);
                    }
                    SaveBuy(txtVoucherNo.Text);
                    SaveSale(txtVoucherNo.Text);
                    
                    MessageBox.Show("Cập nhật vé thành công.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    LoadStatus(true, true, false, false, true, true);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + Environment.NewLine + "Không thể cập nhật vé.", "Aquarius Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        #endregion

        #region Method
        private void GetListProvider()
        {
            try
            {
                ArrayList arr = boProvider.List();
                DataTable dataTable1 = new DataTable("Provider");
                dataTable1.Columns.Add("ProviderId", typeof(String));
                dataTable1.Columns.Add("ProviderName", typeof(String));
                dataTable1.Columns.Add("PersonRepresent", typeof(String));
                foreach (DataObjects.Provider oPro in arr)
                {
                    dataTable1.Rows.Add(new String[] { oPro.ProviderId, oPro.ProviderName, oPro.PersonRepresent });
                }
                cboProviderId.DataSource = dataTable1;
                cboProviderId.ValueMember = "ProviderName";
                cboProviderId.DisplayMember = "ProviderId";
                cboProviderId.SelectedIndex = -1;
                cboProviderId.Text = "";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void GetListCustomer()
        {
            try
            {
                ArrayList arr = boCustomer.List();
                DataTable dataTable1 = new DataTable("Customer");
                dataTable1.Columns.Add("CustomerId", typeof(String));
                dataTable1.Columns.Add("CustomerName", typeof(String));
                dataTable1.Columns.Add("PersonRepresent", typeof(String));
                foreach (DataObjects.Customer oCus in arr)
                {
                    dataTable1.Rows.Add(new String[] { oCus.CustomerId, oCus.CustomerName, oCus.PersonRepresent });
                }
                cboCustomerId.DataSource = dataTable1;
                cboCustomerId.ValueMember = "CustomerName";
                cboCustomerId.DisplayMember = "CustomerId";
                cboCustomerId.SelectedIndex = -1;
                cboCustomerId.Text = "";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadStatusOnce()
        {
            exeCtrl.btnEdit.Enabled = false;
            exeCtrl.btnView.Enabled = false;
            exeCtrl.btnFind.Enabled = false;
            exeCtrl.btnExport.Enabled = false;
            exeCtrl.btnSendmail.Enabled = false;

            exeCtrl.btnEdit.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnView.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnFind.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnExport.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnSendmail.ButtonColor = Color.FromArgb(171, 171, 171);

            exeCtrl.btnEdit.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnView.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnFind.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnExport.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnSendmail.ForeColor = Color.FromArgb(241, 244, 251);
        }

        private void LoadStatus(bool blAdd, bool blDelete, bool blCancel, bool blSave, bool blFunction, bool blPrint)
        {
            exeCtrl.btnAdd.Enabled = blAdd & bAdd;
            exeCtrl.btnDelete.Enabled = blDelete & bDelete;
            exeCtrl.btnCancel.Enabled = blCancel & bCancel;
            exeCtrl.btnSave.Enabled = blSave & bSave;
            exeCtrl.btnFunction.Enabled = blFunction & bFunction;
            exeCtrl.btnPrint.Enabled = blPrint & bPrint;

            exeCtrl.btnAdd.ButtonColor = exeCtrl.btnAdd.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnDelete.ButtonColor = exeCtrl.btnDelete.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnCancel.ButtonColor = exeCtrl.btnCancel.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnSave.ButtonColor = exeCtrl.btnSave.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnFunction.BackColor = exeCtrl.btnFunction.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnPrint.ButtonColor = exeCtrl.btnPrint.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);

            exeCtrl.btnAdd.ForeColor = exeCtrl.btnAdd.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnDelete.ForeColor = exeCtrl.btnDelete.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnCancel.ForeColor = exeCtrl.btnCancel.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnSave.ForeColor = exeCtrl.btnSave.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnFunction.ForeColor = exeCtrl.btnFunction.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnPrint.ForeColor = exeCtrl.btnPrint.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
        }

        private void ClearText()
        {
            objMethod.ClearText(new Control[] { txtVoucherNo, txtEmployeeId, txtFullName, txtRemark, 
                cboProviderId, txtProviderName, txtProviderPersonRepresent, txtTotalBuy, txtDiscountPercent, txtDiscount, txtSumBuy, txtExchangeBuy, txtSumBuyVND,  
                cboCustomerId, txtCustomerName, txtCustomerPersonRepresent, txtTotalSale, txtDiscountPrivateSalePercent, txtDiscountPrivateSale, txtVATPercent, txtVATValue, txtOtherTax, txtOtherCharge, txtSumSale, txtExchangeSale, txtSumSaleVND});
            chkVAT.Checked = false;
            grvDetailBuy.Rows.Clear();
            grvDetailSale.Rows.Clear();
        }

        private void FillData(DataObjects.Voucher oVou)
        {
            try
            {
                txtVoucherNo.Text = oVou.VoucherNo;
                dtpDateOfVoucher.Value = oVou.DateOfVoucher.Value;
                txtEmployeeId.Text = oVou.EmployeeId;
                DataObjects.Employee oEmp = boEmployee.GetObjectByPK(oVou.EmployeeId);
                if (oEmp != null)
                    txtFullName.Text = oEmp.LastName + " " + oEmp.FirstName;
                txtRemark.Text = oVou.Remark;
                //provider
                cboProviderId.Text = oVou.ProviderId;
                txtProviderPersonRepresent.Text = oVou.ProviderPersonRepresent;
                DataObjects.Provider oPro = boProvider.GetObjectByPK(oVou.ProviderId);
                if (oPro != null)
                    txtProviderName.Text = oPro.ProviderName;
                if (oVou.Vat != null)
                    chkVAT.Checked = oVou.Vat.Value;
                txtTotalBuy.Text = objMethod.FormatCurency(oVou.TotalBuy.ToString());
                txtDiscountPercent.Text = oVou.DiscountPercent.ToString();
                txtDiscount.Text = objMethod.FormatCurency(oVou.Discount.ToString());
                txtSumBuy.Text = objMethod.FormatCurency(oVou.SumBuy.ToString());
                if (oVou.CurrencyBuy != null && oVou.CurrencyBuy != "")
                    cboCurrencyBuy.SelectedValue = oVou.CurrencyBuy;
                txtExchangeBuy.Text = objMethod.FormatCurency(oVou.ExchangeBuy.ToString());
                txtSumBuyVND.Text = objMethod.FormatCurency(oVou.SumBuyVnd.ToString());
                //customer  
                cboCustomerId.Text = oVou.CustomerId;
                txtCustomerPersonRepresent.Text = oVou.CustomerPersonRepresent;
                DataObjects.Customer oCus = boCustomer.GetObjectByPK(oVou.CustomerId);
                if (oCus != null)
                    txtCustomerName.Text = oCus.CustomerName;
                txtTotalSale.Text = objMethod.FormatCurency(oVou.TotalSale.ToString());
                txtDiscountPrivateSalePercent.Text = oVou.DiscountPrivatePercent.ToString();
                txtDiscountPrivateSale.Text = objMethod.FormatCurency(oVou.DiscountPrivate.ToString());
                txtVATPercent.Text = oVou.VatPercent.ToString();
                txtVATValue.Text = objMethod.FormatCurency(oVou.VatValue.ToString());
                txtOtherTax.Text = objMethod.FormatCurency(oVou.OtherTax.ToString());
                txtOtherCharge.Text = objMethod.FormatCurency(oVou.OtherCharge.ToString());
                txtSumSale.Text = objMethod.FormatCurency(oVou.SumSale.ToString());
                if (oVou.CurrencySale != null && oVou.CurrencySale != "")
                    cboCurrencySale.SelectedValue = oVou.CurrencySale;
                txtExchangeSale.Text = objMethod.FormatCurency(oVou.ExchangeSale.ToString());
                txtSumSaleVND.Text = objMethod.FormatCurency(oVou.SumSaleVnd.ToString());
                //
                FillBuy(oVou.VoucherNo);
                FillSale(oVou.VoucherNo);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private bool CheckValid()
        {
            if (txtEmployeeId.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn nhân viên.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtEmployeeId.Focus();
                return false;
            }
            else
            {
                DataObjects.Employee oEmp = boEmployee.GetObjectByPK(txtEmployeeId.Text);
                if (oEmp == null)
                {
                    MessageBox.Show("Nhân viên không tồn tại.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtEmployeeId.Focus();
                    return false;
                }
            }

            if (cboProviderId.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn nhà cung cấp.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cboProviderId.Focus();
                return false;
            }
            

            if (cboCustomerId.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn khách hàng.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cboCustomerId.Focus();
                return false;
            }


            if (grvDetailBuy.Rows.Count - 1 <= 0)
            {
                MessageBox.Show("Vui lòng nhập chi tiết mua.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                grvDetailBuy.Focus();
                return false;
            }

            if (grvDetailSale.Rows.Count - 1 <= 0)
            {
                MessageBox.Show("Vui lòng nhập chi tiết bán.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                grvDetailSale.Focus();
                return false;
            }

            if (txtExchangeBuy.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng nhập tỷ giá mua.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtExchangeBuy.Focus();
                return false;
            }
            else
            {
                if (double.Parse(txtExchangeBuy.Text) < 1)
                {
                    MessageBox.Show("Vui lòng nhập tỷ giá mua.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtExchangeBuy.Focus();
                    return false;
                }
            }

            if (txtExchangeSale.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng nhập tỷ giá bán.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtExchangeSale.Focus();
                return false;
            }
            else
            {
                if (double.Parse(txtExchangeSale.Text) < 1)
                {
                    MessageBox.Show("Vui lòng nhập tỷ giá bán.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtExchangeSale.Focus();
                    return false;
                }
            }

            return true;
        }

        private void SaveBuy(string voucher_no)
        {
            //delete
            boVoucherBuy.DeleteByVoucherNo(voucher_no);

            //insert
            DataObjects.VoucherDetailBuy oVouBuy;
            for (int i = 0; i < grvDetailBuy.Rows.Count - 1; i++)
            {
                oVouBuy = new DataObjects.VoucherDetailBuy();
                oVouBuy.VoucherNo = voucher_no;
                oVouBuy.VdbFrom = grvDetailBuy.Rows[i].Cells["colFrom"].Value != null ? grvDetailBuy.Rows[i].Cells["colFrom"].Value.ToString() : "";
                oVouBuy.VdbTo = grvDetailBuy.Rows[i].Cells["colTo"].Value != null ? grvDetailBuy.Rows[i].Cells["colTo"].Value.ToString() : "";
                oVouBuy.FlightNo = grvDetailBuy.Rows[i].Cells["colFltNo"].Value != null ? grvDetailBuy.Rows[i].Cells["colFltNo"].Value.ToString() : "";
                oVouBuy.Class = grvDetailBuy.Rows[i].Cells["colClass"].Value != null ? grvDetailBuy.Rows[i].Cells["colClass"].Value.ToString() : "";
                oVouBuy.DeptDate = grvDetailBuy.Rows[i].Cells["colDeptDate"].Value != null ? Convert.ToDateTime(grvDetailBuy.Rows[i].Cells["colDeptDate"].Value) : DateTime.Now;
                //if (grvDetailBuy.Rows[i].Cells["colDeptDate"].Value.ToString() != "")
                //{
                //    string[] arr = grvDetailBuy.Rows[i].Cells["colDeptDate"].Value.ToString().Split(new char[]{'/'});
                //    oVouBuy.DeptDate = new DateTime(int.Parse(arr[2]), int.Parse(arr[1]), int.Parse(arr[0]));
                //}
                oVouBuy.Pnr = grvDetailBuy.Rows[i].Cells["colPNR"].Value != null ? grvDetailBuy.Rows[i].Cells["colPNR"].Value.ToString() : "";
                oVouBuy.Fare = grvDetailBuy.Rows[i].Cells["colFareBuy"].Value != null ? double.Parse(grvDetailBuy.Rows[i].Cells["colFareBuy"].Value.ToString()) : 0;
                oVouBuy.Tax = grvDetailBuy.Rows[i].Cells["colTaxBuy"].Value != null ? double.Parse(grvDetailBuy.Rows[i].Cells["colTaxBuy"].Value.ToString()) : 0;
                oVouBuy.AddOn = grvDetailBuy.Rows[i].Cells["colAddOnBuy"].Value != null ? double.Parse(grvDetailBuy.Rows[i].Cells["colAddOnBuy"].Value.ToString()) : 0;
                oVouBuy.Amount = grvDetailBuy.Rows[i].Cells["colAmountBuy"].Value != null ? double.Parse(grvDetailBuy.Rows[i].Cells["colAmountBuy"].Value.ToString()) : 0;

                boVoucherBuy.Insert(oVouBuy);
            }
        }

        private void SaveSale(string voucher_no)
        {
            //delete
            boVoucherSale.DeleteByVoucherNo(voucher_no);

            //insert
            DataObjects.VoucherDetailSale oVouSale;
            for (int i = 0; i < grvDetailSale.Rows.Count - 1; i++)
            {
                oVouSale = new DataObjects.VoucherDetailSale();
                oVouSale.VoucherNo = voucher_no;
                oVouSale.Passenger = grvDetailSale.Rows[i].Cells["colPassenger"].Value != null ? grvDetailSale.Rows[i].Cells["colPassenger"].Value.ToString() : "";
                oVouSale.TicketNo = grvDetailSale.Rows[i].Cells["colTicketNo"].Value != null ? grvDetailSale.Rows[i].Cells["colTicketNo"].Value.ToString() : "";
                oVouSale.Remark = grvDetailSale.Rows[i].Cells["colRemark"].Value != null ? grvDetailSale.Rows[i].Cells["colRemark"].Value.ToString() : "";
                oVouSale.Fare = grvDetailSale.Rows[i].Cells["colFareSale"].Value != null ? double.Parse(grvDetailSale.Rows[i].Cells["colFareSale"].Value.ToString()) : 0;
                oVouSale.Tax = grvDetailSale.Rows[i].Cells["colTaxSale"].Value != null ? double.Parse(grvDetailSale.Rows[i].Cells["colTaxSale"].Value.ToString()) : 0;
                oVouSale.AddOn = grvDetailSale.Rows[i].Cells["colAddOnSale"].Value != null ? double.Parse(grvDetailSale.Rows[i].Cells["colAddOnSale"].Value.ToString()) : 0;
                oVouSale.Amount = grvDetailSale.Rows[i].Cells["colAmountSale"].Value != null ? double.Parse(grvDetailSale.Rows[i].Cells["colAmountSale"].Value.ToString()) : 0;

                boVoucherSale.Insert(oVouSale);
            }
        }

        private void InsertVoucherHistory(DataObjects.Voucher oVou)
        {
            //insert
            DataObjects.VoucherHistory oVouHis = new DataObjects.VoucherHistory();
            oVouHis.VoucherNo = oVou.VoucherNo;
            oVouHis.DateCreate = oVou.DateOfVoucher;
            oVouHis.Status = "VSTATUS_1";
            oVouHis.Remark = oVou.Remark;
            oVouHis.UserId = frmMain.CurrentUser.UserId;
            oVouHis.DateInput = DateTime.Now;

            boVoucherHistory.Insert(oVouHis);
        }

        private void UpdateVoucherHistory(DataObjects.Voucher oVou)
        {
            ArrayList arr = boVoucherHistory.GetListByVoucherNoInvoiceNo(oVou.VoucherNo, "");
            foreach (DataObjects.VoucherHistory oVouHis in arr)
            {
                oVouHis.VoucherNo = oVou.VoucherNo;
                oVouHis.DateCreate = oVou.DateOfVoucher;
                oVouHis.Status = "VSTATUS_1";
                oVouHis.Remark = oVou.Remark;
                oVouHis.UserId = frmMain.CurrentUser.UserId;
                oVouHis.DateInput = DateTime.Now;

                //update
                boVoucherHistory.Update(oVouHis);
            }
        }

        private void FillBuy(string voucher_no)
        {
            grvDetailBuy.Rows.Clear();

            ArrayList arr = boVoucherBuy.GetListByVoucherNo(voucher_no);
            if (arr != null)
            {
                if (arr.Count > 0)
                {
                    foreach (DataObjects.VoucherDetailBuy oVouBuy in arr)
                    {
                        int rowIdx = grvDetailBuy.Rows.Add();
                        grvDetailBuy["colFrom", rowIdx].Value = oVouBuy.VdbFrom;
                        grvDetailBuy["colTo", rowIdx].Value = oVouBuy.VdbTo;
                        grvDetailBuy["colFltNo", rowIdx].Value = oVouBuy.FlightNo;
                        grvDetailBuy["colClass", rowIdx].Value = oVouBuy.Class;
                        grvDetailBuy["colDeptDate", rowIdx].Value = oVouBuy.DeptDate;
                        grvDetailBuy["colPNR", rowIdx].Value = oVouBuy.Pnr;
                        grvDetailBuy["colFareBuy", rowIdx].Value = objMethod.FormatCurency(oVouBuy.Fare.ToString());
                        grvDetailBuy["colTaxBuy", rowIdx].Value = objMethod.FormatCurency(oVouBuy.Tax.ToString());
                        grvDetailBuy["colAddOnBuy", rowIdx].Value = objMethod.FormatCurency(oVouBuy.AddOn.ToString());
                        grvDetailBuy["colAmountBuy", rowIdx].Value = objMethod.FormatCurency(oVouBuy.Amount.ToString());
                    }
                }
            }
        }

        private void FillSale(string voucher_no)
        {
            grvDetailSale.Rows.Clear();

            ArrayList arr = boVoucherSale.GetListByVoucherNo(voucher_no);
            if (arr != null)
            {
                if (arr.Count > 0)
                {
                    foreach (DataObjects.VoucherDetailSale oVouSale in arr)
                    {
                        int rowIdx = grvDetailSale.Rows.Add();
                        grvDetailSale["colPassenger", rowIdx].Value = oVouSale.Passenger;
                        grvDetailSale["colTicketNo", rowIdx].Value = oVouSale.TicketNo;
                        grvDetailSale["colRemark", rowIdx].Value = oVouSale.Remark;
                        grvDetailSale["colFareSale", rowIdx].Value = objMethod.FormatCurency(oVouSale.Fare.ToString());
                        grvDetailSale["colTaxSale", rowIdx].Value = objMethod.FormatCurency(oVouSale.Tax.ToString());
                        grvDetailSale["colAddOnSale", rowIdx].Value = objMethod.FormatCurency(oVouSale.AddOn.ToString());
                        grvDetailSale["colAmountSale", rowIdx].Value = objMethod.FormatCurency(oVouSale.Amount.ToString());
                    }
                }
            }
        }

        private void CalculateBuy()
        {
            try
            {
                double total = 0;
                double discount_percent = 0;
                double discount = 0;
                double sum = 0;
                double exchange = 0;
                double sumvnd = 0;
                for (int i = 0; i < grvDetailBuy.Rows.Count - 1; i++)
                {
                    try { total += double.Parse(grvDetailBuy.Rows[i].Cells["colAmountBuy"].Value.ToString()); }
                    catch { }
                }
                try { discount_percent = txtDiscountPercent.Text != "" ? double.Parse(txtDiscountPercent.Text) : 0; }
                catch { }
                discount = Math.Round(total * discount_percent / 100);
                sum = total - discount;
                try {
                    if (cboCurrencyBuy.SelectedValue.ToString().ToUpper() == "CUR_1")
                    {
                        exchange = 1;
                    }
                    else
                    {
                        exchange = txtExchangeBuy.Text != "" ? double.Parse(txtExchangeBuy.Text) : 0;
                    }
                }
                catch { }
                sumvnd = sum * exchange;

                //display
                txtTotalBuy.Text = objMethod.FormatCurency(total.ToString());
                txtDiscountPercent.Text = objMethod.FormatCurency(discount_percent.ToString());
                txtDiscount.Text = objMethod.FormatCurency(discount.ToString());
                txtSumBuy.Text = objMethod.FormatCurency(sum.ToString());
                txtExchangeBuy.Text = objMethod.FormatCurency(exchange.ToString());
                txtSumBuyVND.Text = objMethod.FormatCurency(sumvnd.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void CalcAmountBuy(int index)
        {
            try
            {
                double fare = 0;
                double tax = 0;
                double addon = 0;
                double amount = 0;

                fare = grvDetailBuy.Rows[index].Cells["colFareBuy"].Value != null ? double.Parse(grvDetailBuy.Rows[index].Cells["colFareBuy"].Value.ToString()) : 0;
                tax = grvDetailBuy.Rows[index].Cells["colTaxBuy"].Value != null ? double.Parse(grvDetailBuy.Rows[index].Cells["colTaxBuy"].Value.ToString()) : 0;
                addon = grvDetailBuy.Rows[index].Cells["colAddOnBuy"].Value != null ? double.Parse(grvDetailBuy.Rows[index].Cells["colAddOnBuy"].Value.ToString()) : 0;
                amount = fare + tax + addon;

                grvDetailBuy.Rows[index].Cells["colFareBuy"].Value = objMethod.FormatCurency(fare.ToString());
                grvDetailBuy.Rows[index].Cells["colTaxBuy"].Value = objMethod.FormatCurency(tax.ToString());
                grvDetailBuy.Rows[index].Cells["colAddOnBuy"].Value = objMethod.FormatCurency(addon.ToString());
                grvDetailBuy.Rows[index].Cells["colAmountBuy"].Value = objMethod.FormatCurency(amount.ToString());
            }
            catch (Exception ex)
            {
                //throw ex;
            }
            
        }

        private void CalculateSale()
        {
            try
            {
                double total = 0;
                double vat_percent = 0;
                double vat_value = 0;
                double other_tax = 0;
                double other_charge = 0;
                double sum = 0;
                double exchange = 0;
                double sumvnd = 0;
                for (int i = 0; i < grvDetailSale.Rows.Count - 1; i++)
                {
                    try { total += double.Parse(grvDetailSale.Rows[i].Cells["colAmountSale"].Value.ToString()); }
                    catch { }
                }
                
                //tinh tien ban hang
                try { vat_percent = txtVATPercent.Text != "" ? double.Parse(txtVATPercent.Text) : 0; }
                catch { }
                vat_value = Math.Round(total * vat_percent / 100);

                try { other_tax = txtOtherTax.Text != "" ? double.Parse(txtOtherTax.Text) : 0; }
                catch { }

                try { other_charge = txtOtherCharge.Text != "" ? double.Parse(txtOtherCharge.Text) : 0; }
                catch { }

                sum = total + vat_value + other_tax + other_charge;
                try {
                    if (cboCurrencySale.SelectedValue.ToString().ToUpper() == "CUR_1")
                    {
                        exchange = 1;
                    }
                    else
                    {
                        exchange = txtExchangeSale.Text != "" ? double.Parse(txtExchangeSale.Text) : 0;
                    }
                }
                catch { }
                sumvnd = sum * exchange;

                //display            
                txtTotalSale.Text = objMethod.FormatCurency(total.ToString());
                txtVATPercent.Text = objMethod.FormatCurency(vat_percent.ToString());
                txtVATValue.Text = objMethod.FormatCurency(vat_value.ToString());
                txtOtherTax.Text = objMethod.FormatCurency(other_tax.ToString());
                txtOtherCharge.Text = objMethod.FormatCurency(other_charge.ToString());
                txtSumSale.Text = objMethod.FormatCurency(sum.ToString());
                txtExchangeSale.Text = objMethod.FormatCurency(exchange.ToString());
                txtSumSaleVND.Text = objMethod.FormatCurency(sumvnd.ToString());

                //GIAM GIA RIENG
                double discount_private_percent = 0;
                double discount_private = 0; 
                try { discount_private_percent = txtDiscountPrivateSalePercent.Text != "" ? double.Parse(txtDiscountPrivateSalePercent.Text) : 0; }
                catch { }
                discount_private = Math.Round(total * discount_private_percent / 100);
                txtDiscountPrivateSalePercent.Text = objMethod.FormatCurency(discount_private_percent.ToString());
                txtDiscountPrivateSale.Text = objMethod.FormatCurency(discount_private.ToString());

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void CalculateSaleDiscount(bool percent)
        {
            try
            {
                double total = 0;
                
                double discount_private_percent = 0;
                double discount_private = 0;
                
                for (int i = 0; i < grvDetailSale.Rows.Count - 1; i++)
                {
                    try { total += double.Parse(grvDetailSale.Rows[i].Cells["colAmountSale"].Value.ToString()); }
                    catch { }
                }

                //tinh rieng
                if (percent)
                {
                    try { discount_private_percent = txtDiscountPrivateSalePercent.Text != "" ? double.Parse(txtDiscountPrivateSalePercent.Text) : 0; }
                    catch { }
                    discount_private = Math.Round(total * discount_private_percent / 100);
                }
                else
                {
                    try { discount_private = txtDiscountPrivateSale.Text != "" ? double.Parse(txtDiscountPrivateSale.Text) : 0; }
                    catch { }
                    discount_private_percent = Math.Round(discount_private * 100 / total, 1);
                }

                //display
                txtDiscountPrivateSalePercent.Text = objMethod.FormatCurency(discount_private_percent.ToString());
                txtDiscountPrivateSale.Text = objMethod.FormatCurency(discount_private.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void CalcAmountSale(int index)
        {
            try
            {
                double fare = 0;
                double tax = 0;
                double addon = 0;
                double amount = 0;

                fare = grvDetailSale.Rows[index].Cells["colFareSale"].Value != null ? double.Parse(grvDetailSale.Rows[index].Cells["colFareSale"].Value.ToString()) : 0;
                tax = grvDetailSale.Rows[index].Cells["colTaxSale"].Value != null ? double.Parse(grvDetailSale.Rows[index].Cells["colTaxSale"].Value.ToString()) : 0;
                addon = grvDetailSale.Rows[index].Cells["colAddOnSale"].Value != null ? double.Parse(grvDetailSale.Rows[index].Cells["colAddOnSale"].Value.ToString()) : 0;
                amount = fare + tax + addon;

                grvDetailSale.Rows[index].Cells["colFareSale"].Value = objMethod.FormatCurency(fare.ToString());
                grvDetailSale.Rows[index].Cells["colTaxSale"].Value = objMethod.FormatCurency(tax.ToString());
                grvDetailSale.Rows[index].Cells["colAddOnSale"].Value = objMethod.FormatCurency(addon.ToString());
                grvDetailSale.Rows[index].Cells["colAmountSale"].Value = objMethod.FormatCurency(amount.ToString());
            }
            catch (Exception ex)
            {
                //throw ex;
            }

        }

        private void GetDiscountProvider()
        {
            if (txtVoucherNo.Text != "")
            {
                Business.PartnerLabourContract boPLC = new Business.PartnerLabourContract();
                DataObjects.PartnerLabourContract oPLC = boPLC.GetObjectByDate(cboProviderId.Text, dtpDateOfVoucher.Value);
                if (oPLC != null)
                {
                    txtDiscountPercent.Text = oPLC.Discount.ToString();
                }
                else
                {
                    txtDiscountPercent.Text = "0";
                }
            }
            
        }

        private void GetDiscountCustomer()
        {
            if (txtVoucherNo.Text != "")
            {
                Business.PartnerLabourContract boPLC = new Business.PartnerLabourContract();
                DataObjects.PartnerLabourContract oPLC = boPLC.GetObjectByDate(cboCustomerId.Text, dtpDateOfVoucher.Value);
                if (oPLC != null)
                {
                    txtDiscountPrivateSalePercent.Text = oPLC.Discount.ToString();
                }
                else
                {
                    txtDiscountPrivateSalePercent.Text = "0";
                }
            }
            
        }

        private bool CheckIsExist(string voucher_no)
        {
            DataObjects.Voucher oVou = boVoucher.GetObjectByPK(voucher_no);
            if (oVou != null)
            {
                return true;
            }
            return false;
        }
        #endregion     

        
    }
}
